package popedom

import (
	"strconv"
	"strings"

	"shqsoft.cn/pas3ui/base"
	"shqsoft.cn/pas3ui/popedom/entity"
)

// TreeNode 树结构体
type TreeNode struct {
	Key      string     `json:"key"`
	Title    string     `json:"title"`
	Children []TreeNode `json:"children"`
}

// GetPermissionTree 获取权限第一层树
func GetPermissionTree() ([]TreeNode, error) {
	return getPermissionTreeNode(0)
}

// GetPermissionTreeNode 根据父节点的ID获取权限树结构
func getPermissionTreeNode(pID int) ([]TreeNode, error) {
	var perms []entity.Permission
	err := base.MYDB.Where(`"ParentPermissionId"=? AND "IsUse"=1 ORDER BY "SortNo"`, pID).Find(&perms).Error
	if err != nil {
		return nil, err
	}
	pLen := len(perms)
	treeNodes := make([]TreeNode, pLen)
	for i, ps := range perms {
		treeNodes[i].Key = strconv.Itoa(ps.ID)
		treeNodes[i].Title = ps.PermissionName
		children, err := getPermissionTreeNode(ps.ID)
		if err != nil {
			return nil, err
		}
		if len(children) == 0 {
			psType := strings.Split(ps.PermissionType, ",")
			children, err = getPermissionTypeTreeNode(ps.ID, psType)
			if err != nil {
				return nil, err
			}
		}
		treeNodes[i].Children = children
	}
	return treeNodes, nil
}

// getPermissionTypeTreeNode 根据父节点的ID获取权限树结构
func getPermissionTypeTreeNode(ID int, pTypes []string) ([]TreeNode, error) {
	var permTypes []entity.PermissionType
	err := base.MYDB.Where(`"PTID" in(?)`, pTypes).Find(&permTypes).Error
	if err != nil {
		return nil, err
	}
	pLen := len(permTypes)
	treeNodes := make([]TreeNode, pLen)
	for i, pt := range permTypes {
		treeNodes[i].Key = strconv.Itoa(ID) + ":" + pt.PTID
		treeNodes[i].Title = pt.PTNM
	}
	return treeNodes, nil
}

// GetOrganTree 获取用户第一层树
func GetOrganTree() ([]TreeNode, error) {
	return getOrganTreeNode(0)
}

// GetOrganTreeNode 根据父节点的ID获取部门结构
func getOrganTreeNode(oID int) ([]TreeNode, error) {
	var organ []entity.Organ
	err := base.MYDB.Where(`ParentOrganID=?`, oID).Order(`OrderKey`).Find(&organ).Error
	if err != nil {
		return nil, err
	}
	oLen := len(organ)
	treeNodes := make([]TreeNode, oLen)
	for i, po := range organ {
		treeNodes[i].Key = strconv.Itoa(po.ID)
		treeNodes[i].Title = po.OrganName
		children, err := getOrganTreeNode(po.ID)
		if err != nil {
			return nil, err
		}
		userChildren, err := getUserTreeNode(po.ID)
		if err != nil {
			return nil, err
		}
		if children == nil {
			children = userChildren
		} else {
			children = append(children, userChildren...)
		}
		treeNodes[i].Children = children
	}
	return treeNodes, nil
}

// getUserTreeNode 根据父节点的ID获取用户树结构
func getUserTreeNode(ID int) ([]TreeNode, error) {
	var users []entity.SysUser
	err := base.MYDB.Where(`OrganID =? and ID>=0`, ID).Find(&users).Error
	if err != nil {
		return nil, err
	}
	uLen := len(users)
	treeNodes := make([]TreeNode, uLen)
	for i, u := range users {
		treeNodes[i].Key = "u:" + strconv.Itoa(u.ID)
		treeNodes[i].Title = u.Name
	}
	return treeNodes, nil
}

// GetCheckedRolePerms 获取选中的角色权限
func GetCheckedRolePerms(rID int) ([]string, error) {
	var rolesPerms []entity.RolePermission
	err := base.MYDB.Where(`"RoleId" =?`, rID).Find(&rolesPerms).Error
	if err != nil {
		return nil, err
	}
	rolePermsKeys := make([]string, 0, 50)
	for _, rps := range rolesPerms {
		ptypes := strings.Split(rps.PermissionType, ",")
		for _, ps := range ptypes {
			keys := strconv.Itoa(rps.PermissionId) + ":" + ps
			rolePermsKeys = append(rolePermsKeys, keys)
		}
	}
	return rolePermsKeys, nil
}

// GetCheckedRoleUsers 获取选中的角色用户
func GetCheckedRoleUsers(rID int) ([]string, error) {
	var userRole []entity.UserRole
	err := base.MYDB.Where(`"RoleId" =?`, rID).Find(&userRole).Error
	if err != nil {
		return nil, err
	}
	roleUserKeys := make([]string, 0, 50)
	for _, ru := range userRole {
		keys := "u:" + strconv.Itoa(*ru.UserId)
		roleUserKeys = append(roleUserKeys, keys)
	}
	return roleUserKeys, nil
}

// GetCheckedUserPerms 获取选中的用户权限
func GetCheckedUserPerms(uID int) ([]string, error) {
	var usersPerms []entity.UserPermission
	err := base.MYDB.Where(`"UserId" =?`, uID).Find(&usersPerms).Error
	if err != nil {
		return nil, err
	}
	userPermsKeys := make([]string, 0, 50)
	for _, ups := range usersPerms {
		ptypes := strings.Split(ups.PermissionType, ",")
		for _, ps := range ptypes {
			keys := strconv.Itoa(ups.PermissionId) + ":" + ps
			userPermsKeys = append(userPermsKeys, keys)
		}
	}
	return userPermsKeys, nil
}

// GetCheckedUserRoles 获取选中的用户角色
func GetCheckedUserRoles(uID int) ([]string, error) {
	var userRole []entity.UserRole
	err := base.MYDB.Where(`"UserId" =?`, uID).Find(&userRole).Error
	if err != nil {
		return nil, err
	}
	userRoleKeys := make([]string, 0, 50)
	for _, ur := range userRole {
		keys := strconv.Itoa(ur.RoleId)
		userRoleKeys = append(userRoleKeys, keys)
	}
	return userRoleKeys, nil
}

// GetRole 根据角色ID获取角色
func GetRole(roleID int) (*entity.SysRole, error) {
	role := entity.SysRole{}
	err := base.MYDB.First(&role, roleID).Error
	if err != nil {
		return nil, err
	}
	return &role, nil
}
